package com.hczx.caxa.service;

import com.alibaba.fastjson.JSONArray;
import com.hczx.caxa.bean.SignInfoBean;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

@Service
public class SignService {

    private static Logger logger = LoggerFactory.getLogger(SignService.class);

    private final MinioService minioService;
    private final LogFileService logFile;

    public SignService(MinioService minioService, LogFileService logFile) {
        this.minioService = minioService;
        this.logFile = logFile;
    }

    public String doSignDrawing(StringBuffer loggerBuffer, MultipartFile pdfFile, String signInfo) throws Exception {
        String targetPath = StringUtils.EMPTY;

        loggerBuffer.append(logFile.now()).append("  -->开始执行签名......").append("\n");

        try (InputStream inputStream = pdfFile.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {

            String name = pdfFile.getOriginalFilename();
            String targetName = "/sign/sign_" + name;

            PdfReader reader = new PdfReader(inputStream);
            PdfStamper stamper = new PdfStamper(reader, outputStream);

            BaseFont baseFont = BaseFont.createFont("/fonts/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            int totalPages = reader.getNumberOfPages();
            for (int i = 1; i <= totalPages; i++) {
                PdfContentByte content = stamper.getOverContent(i);

                float fontsize = 12;
                content.setFontAndSize(baseFont, fontsize);
                content.beginText();
                float rotation = 0;

                List<SignInfoBean> signInfos = JSONArray.parseArray(signInfo, SignInfoBean.class);
                signInfos.stream()
                        .filter(item -> ObjectUtils.allNotNull(item.getXc(), item.getYc(), item.getContent()))
                        .forEach(item -> {
                            float x = Float.valueOf(item.getXc());
                            float y = Float.valueOf(item.getYc());
                            //showTextAligned 方法的参数分别是（文字对齐方式，位置内容，输出水印X轴位置，Y轴位置，旋转角度）
                            content.showTextAligned(Element.ALIGN_LEFT, item.getContent(), x, y, rotation);
                        });

                content.endText();
            }

            stamper.close();
            reader.close();

            loggerBuffer.append(logFile.now()).append("  -->开始上传Minio").append("\n");

            loggerBuffer.append(logFile.now()).append("  -->上传Minio位置：").append(targetName).append("\n");

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            targetPath = minioService.upload(byteArrayInputStream, targetName, "application/pdf");

            loggerBuffer.append(logFile.now()).append("  -->上传Minio地址:").append("\n");
            loggerBuffer.append(logFile.now()).append(targetPath).append("\n");

        } catch (Exception e) {
            logger.error("签名出错，详情请查看日志！\n", e);
            throw new Exception("签名出错，详情请查看日志！");
        }
        return targetPath;
    }

}
